package com.snail.snailvr.mvp.presenter;

import android.util.Log;
import android.view.View;

import com.snail.snailvr.R;
import com.snail.snailvr.VRApp;
import com.snail.snailvr.model.UpdateModel;
import com.snail.snailvr.mvp.views.BaseView;
import com.snail.snailvr.mvp.views.VersionUpdateView;
import com.snail.snailvr.network.VRApi;
import com.snail.snailvr.utils.NetworkUtil;
import com.snail.snailvr.utils.ToastUtils;
import com.snail.snailvr.utils.Util;

import java.lang.ref.WeakReference;

public class VersionUpdatePresenter extends Presenter {

    private boolean showToast = false;

    private WeakReference<VersionUpdateView> mBaseViewWeakReference;

    private View toastView;

    public VersionUpdatePresenter(VersionUpdateView baseView, View toastView) {
        mBaseViewWeakReference = new WeakReference<>(baseView);
        this.toastView = toastView;

    }

    public void loadData(boolean isShowToast) {
        showToast = isShowToast;
        loadData();
    }

    @Override
    public BaseView getMvpView() {
        return mBaseViewWeakReference.get();
    }

    @Override
    public void success(Object o) {
        Log.i("update", "success");
        if (o instanceof UpdateModel) {
            Log.i("update", "instance of updateMode");

            UpdateModel model = (UpdateModel) o;

            if (model != null) {
                Log.i("update", "instance of updateMode != null");
                mBaseViewWeakReference.get().onRequestComplete(model, showToast);
            } else {
                Log.i("update", "instance of updateMode == null");
                if (showToast) {
                    ToastUtils.makeToastColorShow(VRApp.getInstance(), toastView, VRApp.getInstance().getResources().getString(R.string.check_update_fail));
                }
            }
        }
    }

    @Override
    public void loadData() {
        if (NetworkUtil.isNetworkConnected()) {
            VRApi.requestVersionUpdateJson(String.valueOf(Util.getSelfVersionCode()), this);
            Log.i("update","loadData : versionCode:" + Util.getSelfVersionCode());
        } else {
            getMvpView().showError();
        }

    }

    public void destroy() {
        toastView = null;
    }
}
